package com.rongchuang.controller;

import com.rongchuang.dto.SupplyDemandDTO;
import com.rongchuang.dto.UserDTO;
import com.rongchuang.service.SupplyDemandService;
import com.rongchuang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("supply-demand")
public class SupplyDemandController {

    @Autowired
    private SupplyDemandService supplyDemandService;

    @Autowired
    private UserService userService;

    /**
     * 修改供求信息
     * @param dto 参数
     */
    @PostMapping("modify")
    public void modify(HttpServletRequest request,
                       @RequestBody SupplyDemandDTO dto) {
        Long associationId = getAssociationIdByUserId(request);
        dto.setAssociationId(associationId);
        supplyDemandService.modify(dto);
    }

    /**
     * 供求信息分页查询
     * @param pageNum 第几页
     * @param pageSize 一页条数
     * @return 会员信息
     */
    @GetMapping("page")
    public Page<SupplyDemandDTO> pageSearch(@RequestParam(defaultValue = "0") int pageNum,
                                            @RequestParam(defaultValue = "10") int pageSize) {
        return supplyDemandService.pageSearch(pageNum, pageSize);
    }

    /**
     * 获取供求详情
     * @param id 会员id
     * @return 会员信息
     */
    @GetMapping("detail/{id}")
    public SupplyDemandDTO detail(@PathVariable Long id) {
        return supplyDemandService.getDetail(id);
    }

    /**
     * 根据用户id获取所属商会id
     */
    private Long getAssociationIdByUserId(HttpServletRequest request) {
        // 获取用户id
        Long userId = (Long)request.getAttribute("userId");
        UserDTO userDTO = userService.getDetail(userId);
        return userDTO.getAssociationId();
    }
}
